<?php

namespace app\api\controller;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Children;
use app\admin\model\market\Acceleration;
use app\admin\model\shopro\goods\SkuPrice;
use app\admin\model\shopro\order\Action;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use app\admin\model\shopro\user\WalletLog;
use app\common\controller\Api;
use app\common\model\shopro\DividendLog;
use app\common\model\shopro\ReleaseAccelerateLogModel;
use app\common\model\shopro\ReleaseAccelerateMarketplaceLogModel;
use app\common\model\shopro\ReleaseLog;
use app\common\model\shopro\Shop;
use app\common\model\User;
use app\common\model\Userchildren;
use fast\Random;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function calculateProfitShare($level, $baseShare, $decrement)
    {
        $profitShare = $baseShare - ($level - 1) * $decrement; // 计算分成比例

        if ($profitShare <= 0) {
            $profitShare = 0;
        }

        return $profitShare;
    }

    /**
     * 获取对应分销商等级、对应层级的商品佣金规则
     */
    public function getCommissionLevelRule($agentLevel)
    {
        $accelerationModel = new Acceleration();
        $jcRules           = $accelerationModel->where(['status' => 1])->select();
        foreach ($jcRules as $v) {
            if ($v['id'] == $agentLevel) {
                return $v;
            }
        }
        return false;
    }

    /**
     * 计算对应规则分销佣金
     *
     * @param  int  $commissionRule  分销规则
     * @param  int  $amount  结算价格
     * @param  int  $goodsNum  购买数量
     */
    private function caculateGoodsCommission($commissionRule, $team_amount, $string = 'accelerate_scale')
    {
        $bili       = $commissionRule[$string] / 100;
        $commission = bcmul($team_amount, $bili, 2);
        return $commission;
    }

    /**
     * @menu 释放
     * @Author:男人的坏
     * @Date:2024-04-16 16:49
     */
    public function accelerateshifang($data, $event)
    {

        $golen_scale = config('site.golen_scale') / 100;        //金豆比例
        $slive_scale = (100 - config('site.golen_scale')) / 100;//银豆比例
        $userModel   = new \app\common\model\User();
        $result      = false;
        $all_score   = 0;
        $all_golden  = 0;
        $all_silver  = 0;
        $user_num    = 0;
        $user_ids    = '';
        if ($event == 'pingji') {
            $memo = '平级奖励';
        } else {
            $memo = '市场补贴励';
        }
        foreach ($data as $k => $v) {
            $userInfo = $userModel->where(['id' => $v['user_id']])->field('id,score,is_old')->find();
            if ($userInfo->score > 0) {
                $release = $v['amount'];
                if ($userInfo->score <= $release) {
                    $release = $userInfo->score;
                }
                $all_score += $release;

                $user_num++;
                $user_ids   .= ','.$v['user_id'];
                $result     = WalletService::change($v['user_id'], 'score', -$release, $event, [],
                    $memo);
                $golden     = bcmul($release, $golen_scale, 2);
                $all_golden += $golden;
                $result     = WalletService::change($v['user_id'], 'golden', $golden, $event, [],
                    $memo.'积分转化金豆');
                $slive      = bcmul($release, $slive_scale, 2);
                $all_silver += $slive;
                $result     = WalletService::change($v['user_id'], 'silver', $slive, $event, [],
                    $memo.'积分转化银豆');
            }

        }

        $arr['result']     = $result;
        $arr['user_ids']   = trim($user_ids, ',');
        $arr['user_num']   = $user_num;
        $arr['all_golden'] = $all_golden;
        $arr['all_silver'] = $all_silver;
        $arr['all_score']  = $all_score;
        return $arr;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public function ceshi()
    {
        $data = db('user')->select();
        foreach ($data as $k=>$v){
          $r =  db('user')->where(['id'=>$v['id']])->update(['password'=>$this->getEncryptPassword('a12345',$v['salt'])]);
            dump($r);
        }

//        dump( config('site.is_release'));
        exit();

//                $url = "https://api.ku55.cn/index.php?s=/store/user/getChildLists&userId=645";
//
//        $ch          = curl_init($url);
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
////        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array (
//                'Content-Type: application/json',
//                //                'Content-Length: '.strlen($data_string),
//                'Access-Token:2e12f4bbb479a77af9dae58c30580413'
//            )
//        );
//
//        $result = json_decode(curl_exec($ch), true);
//        cache('data_two',$result);
//        dump($result);exit();
//        $data = cache('data_two')[''];
//        $data = db('user')->select();
//        foreach ($data as $k=>$v){
//            $model = new Userchildren();
//            $to_insert = [['member_id' => $v['parent_user_id'], 'level' => 1, 'children_id' => $v['id']]];
//            $model->where('children_id', $v['parent_user_id'])->chunk(100000, function($items) use ($v, &$to_insert,$model) {
//                foreach ($items as $item) {
//                    $to_insert[] = [
//                        'member_id' => $item->member_id,
//                        'level' => $item['level'] + 1,
//                        'children_id' => $v['id'],
//                    ];
//                }
//
//                $model->insertAll($to_insert);
//                $to_insert = [];
//            },'level','asc');
//            if (!empty($to_insert)) {
//                $model->insertAll($to_insert);
//            }
//        }
//        exit();

//        $this->digui(cache('data_two')['data']['list']);
//        $data = cache('data_two');
//
//        foreach ($data as $k=>$v){
//            $model = new Userchildren();
//            $to_insert = [['member_id' => $v['parent_id'], 'level' => 1, 'children_id' => $v['id']]];
//            $model->where('children_id', $v['parent_id'])->chunk(100000, function($items) use ($v, &$to_insert,$model) {
//                foreach ($items as $item) {
//                    $to_insert[] = [
//                        'member_id' => $item->member_id,
//                        'level' => $item['level'] + 1,
//                        'children_id' => $v['id'],
//                    ];
//                }
//
//                $model->insertAll($to_insert);
//                $to_insert = [];
//            },'level','asc');
//            if (!empty($to_insert)) {
//                $model->insertAll($to_insert);
//            }
//        }

        $data = db('user')->select();
        $url = "https://api.ku55.cn/index.php?s=/store/user/list&page=1";
        foreach ($data as $k=>$v){
            $url .='&search='.$v['mobile'];
            $ch          = curl_init($url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    //        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array (
                    'Content-Type: application/json',
                    //                'Content-Length: '.strlen($data_string),
                    'Access-Token:2e12f4bbb479a77af9dae58c30580413'
                )
            );
            $result = json_decode(curl_exec($ch), true);
            $result = $result['data']['list']['data'][0];
            $up['money'] = $result['balance'];
            $up['golden'] = $result['golden'];
            $up['silver'] = $result['silver'];
            $up['gold'] = $result['gold'];
            $up['invite_code'] = $result['invite_code'];
            $up['platform'] = $result['platform'];
            $up['user_json'] = json_encode($result,true);
           $r=  db('user')->where(['id'=>$result['user_id']])->update($up);
            dump($r);
        }
        exit();
//        dump($data);

//        exit();

        //        $data = db('agentreward_log')->select();
//        $arr  = [];
//        $accelerateLogModel = new ReleaseAccelerateMarketplaceLogModel();
//        foreach ($data as $k => $v) {
//            if (!isset($arr[$v['user_id'].'-'.$v['type']])) {
//                $arr[$v['user_id'].'-'.$v['type']]               = $v;
//            } else {
//                $arr[$v['user_id'].'-'.$v['type']]['amount'] += $v['amount'];
//            }
//        }
//        $jichaArray = [];
//        $pingjiArray = [];
//        $key = -1;
//        foreach ($arr as $kk => $vv) {
//            $key ++;
//            if ($vv['type'] == 1) {
//                $accelerate_scale_two = $vv['accelerate_scale_two']??0;
//                $accelerate_scale = ($vv['accelerate_scale']-$accelerate_scale_two)/100;
//                $amount = bcmul($vv['amount'], $accelerate_scale,2);//市场补贴励
//                $jichaArray[$key]['user_id'] = $vv['user_id'];
//                $jichaArray[$key]['amount'] = $amount;
//            }else{
//                $pingjiArray[$key]['user_id'] = $vv['user_id'];
//                $pingjiArray[$key]['amount'] = bcmul($vv['amount'], 0.01,2);;
//            }
//        }
//        if ($jichaArray) {
//            $inser = $this->accelerateshifang($jichaArray,'jicha');
//            if ($inser['result']) {
//                unset($inser['result']);
//                $inser['shifang_type'] = 1;
//                $accelerateLogModel->create($inser);
//            }
//        }
//        if ($pingjiArray) {
//            $inser = $this->accelerateshifang($pingjiArray,'pingji');
//            if ($inser['result']) {
//                unset($inser['result']);
//                $inser['shifang_type'] = 2;
//                $accelerateLogModel->create($inser);
//            }
//        }
//        db('agentreward_log')->whereTime('createtime', 'd')->delete();
//        exit();
    }

    public function digui($data){
        if(!empty($data['children'])){
            foreach ($data['children'] as $k=>$v){
                $inser['id'] = $v['user_id'];
                $inser['parent_user_id'] = $v['parent_id'];
                $inser['mobile'] = $v['mobile'];
                $inser['nickname'] = $v['nick_name'];
                $inser['level']  = $v['level'];
//                $inser['level_label']  = $v['level_label'];
                $inser['group_id']  = 1;
                $inser['salt']  = Random::alnum();
                $inser['invite_code'] = Random::alnum();
//            dump($inser);
                db('user')->insert($inser);
                if(!empty($v['children'])){
                    $this->digui($v);
                }
            }
        }

    }
    /**
     * @menu 分积分
     * @Author:男人的坏
     * @Date:2024-04-15 15:22
     */
    public function fenyong($order, $user)
    {
        $skuPriceModel         = new SkuPrice();
        $goodsModel            = new \app\admin\model\shopro\goods\Goods();
        $gift_score            = 0;
        $gift_silver           = 0;
        $gift_firepower        = 0;
        $gift_firepower_parent = 0;
        foreach ($order['items'] as $k => $v) {
            $goodsInfo = $goodsModel->where(['id' => $v->goods_id, 'type' => 'normal'])->find();
            if ($goodsInfo) {
                //分佣商品产生分佣
                $skuPriceInfo = $skuPriceModel->where(['id' => $v->goods_sku_price_id])->find();
                if ($skuPriceInfo) {
                    if (!$order['goods_golden'] && $order['goods_silver']) {
                        $gift_score += bcmul($v->pay_fee, ($skuPriceInfo->gift_score / 100), 2);
                    } else {
                        $pay_fee = $v->pay_fee;
                        if ($order['goods_golden'] > 0) {
                            $jie_money = bcmul($v->pay_fee, ($skuPriceInfo->golden_scale / 100), 2);
                            $pay_fee   -= $jie_money;
                        }
                        if ($order['goods_silver'] > 0) {
                            $jie_money = bcmul($pay_fee - $jie_money, ($skuPriceInfo->silver_scale / 100), 2);
                            $pay_fee   -= $jie_money;
                        }
                        $gift_score += bcmul($pay_fee, ($skuPriceInfo->gift_score / 100), 2);
                    }
                }
                //赠送银豆
                if ($goodsInfo->silver_type == 'silver_scale_type') {
                    $gift_silver += bcmul($v->pay_fee, ($goodsInfo->silver_type_num / 100), 2);
                } elseif ($goodsInfo->firepower_type == 'silver_immobilization') {
                    $gift_silver = $goodsInfo->silver_type_num;
                }
                //自购赠送火力
                if ($goodsInfo->firepower_type == 'firepower_scale') {
                    $gift_firepower += bcmul($v->pay_fee, ($goodsInfo->firepower_num / 100), 2);
                } elseif ($goodsInfo->firepower_type == 'firepower_immobilization') {
                    $gift_firepower = $goodsInfo->firepower_num;
                }
                //上级赠送火力
                if ($user->parent_user_id > 0) {
                    if ($goodsInfo->firepower_parent_type == 'firepower_parent_scale') {
                        $gift_firepower_parent += bcmul($v->pay_fee, ($goodsInfo->firepower_parent_num / 100), 2);
                    } elseif ($goodsInfo->firepower_type == 'firepower_parent_immobilization') {
                        $gift_firepower_parent = $goodsInfo->firepower_parent_num;
                    }
                }
            }
        }
        $params['id']  = $order['user_id'];
        $params['ext'] = ['order_id' => $order['id']];
        if ($gift_score) {
//            $params['type']   = 'score';
//            $params['amount'] = $gift_score;
//            $params['memo']   = '自购奖励';
//            Db::transaction(function () use ($params) {
//                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
//                    $params['memo']);
//            });
        }
        //赠送银豆
        if ($gift_silver) {
            $params['type']   = 'silver';
            $params['amount'] = $gift_silver;
            $params['memo']   = '自购奖励';
            Db::transaction(function () use ($params) {
                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
                    $params['memo']);
            });
        }
        //赠送火力
        if ($gift_firepower) {
            $params['type']   = 'firepower';
            $params['amount'] = $gift_firepower;
            $params['memo']   = '自购奖励';
            Db::transaction(function () use ($params) {
                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
                    $params['memo']);
            });
        }
        if ($gift_firepower_parent) {
            $params['type']                  = 'firepower';
            $params['amount']                = $gift_firepower_parent;
            $params['memo']                  = '下级贡献';
            $params['id']                    = $user->parent_user_id;
            $params['ext']['parent_user_id'] = $user->parent_user_id;
            Db::transaction(function () use ($params) {
                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order_gongxian',
                    $params['ext'],
                    $params['memo']);
            });
        }
        exit();
        //帕点分红
        $childrenData = Children::where(['children_id' => $order['user_id']])->order('level asc')->column('member_id');
        if ($childrenData) {
            $userModel = new \app\common\model\User();
            $userArray = [];
            $ke        = -1;
            foreach ($childrenData as $kk => $vv) {
                $pa_rate = $userModel->where(['id' => $vv, 'pa_rate' => ['gt', 0]])->value('pa_rate');
                if ($pa_rate) {
                    $ke++;
                    $userArray[$ke]['user_id'] = $vv;
                    $userArray[$ke]['pa_rate'] = $pa_rate;
                }
            }
            if (!empty($userArray[0]['pa_rate'])) {
                $is_two = true;
                if ($userArray[0]['pa_rate'] >= 15 || empty($userArray[1]['pa_rate'])) {
                    $is_two = false;
                }
                $order_amount             = $order->order_amount;
                $gold                     = bcmul($order_amount, ($userArray[0]['pa_rate'] / 100), 2);
                $params['type']           = 'gold';
                $params['amount']         = $gold;
                $params['memo']           = 'PA点收益';
                $params['id']             = $userArray[0]['user_id'];
                $params['ext']['user_id'] = $userArray[0]['user_id'];
                Db::transaction(function () use ($params) {
                    return WalletService::change($params['id'], $params['type'], $params['amount'], 'order',
                        $params['ext'],
                        $params['memo']);
                });
                if ($is_two) {
                    $pa_rate                  = $userArray[1]['pa_rate'] - $userArray[0]['pa_rate'];
                    $gold                     = bcmul($order_amount, ($pa_rate / 100), 2);
                    $params['type']           = 'gold';
                    $params['amount']         = $gold;
                    $params['memo']           = 'PA点收益';
                    $params['id']             = $userArray[1]['user_id'];
                    $params['ext']['user_id'] = $userArray[0]['user_id'];;
                    Db::transaction(function () use ($params) {
                        return WalletService::change($params['id'], $params['type'], $params['amount'], 'order',
                            $params['ext'],
                            $params['memo']);
                    });
                }
            }

        }

    }

    public function index()
    {
        $this->ceshi();exit();
        $order = Order::where(['id'=>140])->find();
        $items = OrderItem::where('order_id', 140)->select();
        foreach ($items as $item) {
            $item->ext = array_merge($item->ext, ['confirm_time' => time()]);
            $item->dispatch_status = OrderItem::DISPATCH_STATUS_GETED;        // 确认收货
            $item->save();

            // 订单确认收货后
            $params = ['order' => $order, 'item' => $item];
            $order = $params['order'];
            $item = $params['item'];
            if($order['shop_id']){
                if($item['goods_type'] == 'normal'){
                    $inc = 'normal_money';
                    $order_amount = $item->pay_fee;
                }else{
                    $inc = 'virtual_money';
                    $order_amount = $item->pay_fee;
                }
                $query = Shop::where(['id'=>$order['shop_id']]);
                $query->setInc($inc,$item->pay_fee);
                $shopInfo = $query->find();
                $shop_performance_fh = config('site.shop_performance_fh')/100;
                $golden            = bcmul($order_amount, $shop_performance_fh, 2);
                WalletService::change($shopInfo['user_id'], 'golden', $golden,
                    'xinzeng_golden',
                    [],
                    '新增业绩补贴');
            }
        }
        exit();


        $userModel        = new User();
        $dividendLogModel = new DividendLog();
        $orderModel       = new Order();
        $query            = $orderModel->whereNull('activity_type')->whereIn('status',
            'paid,completed')->whereTime('createtime',
            'd');
        $order_amount     = $query->sum('order_amount');
        if ($order_amount > 0) {
            $childrenModel = new Children();
            $userData      = $userModel->with([
                'acceleration' => function ($query) {
                    $query->field('id,dividend');
                }
            ])->where(['score' => ['gt', 0]])->whereIn('level', '5,6,7')->field('id,score,level')->select();

            $userData    = collection($userData)->each(function ($query) use ($childrenModel) {
                $query->children_id = $childrenModel->where(['member_id' => $query->id])->column('children_id');
            });
            $fenhongData = [];
            foreach ($userData as $k => $v) {
                if ($v->children_id) {
                    $userYeji = $orderModel->whereNull('activity_type')->whereIn('user_id',
                        $v->children_id)->whereIn('status',
                        'paid,completed')->whereTime('createtime', 'd')->sum('order_amount');
                    if ($userYeji) {
                        $dividend = $v->acceleration->dividend / 100;
                        $golden   = bcmul($order_amount, $dividend, 2);
                        $golden   = bcmul($golden, '0.7', 2);
                        //对应等级总业绩 / 订单总业绩 * 订单总业绩的70% / 总人数
                        if (isset($fenhongData[$v->level])) {
                            $fenhongData[$v->level]['num']     += 1;
                            $fenhongData[$v->level]['user_id'] .= ','.$v->id;
                        } else {
                            $fenhongData[$v->level]['num']     = 1;
                            $fenhongData[$v->level]['user_id'] = $v->id;
                            $fenhongData[$v->level]['golden']  = $golden;
                            $fenhongData[$v->level]['yeji']    = $userYeji;
                        }
                    }
                }
            }
        }
        if ($fenhongData) {
            foreach ($fenhongData as $key => $val) {
                $user_gold = round($val['golden'] / $val['num'], 2);
                $arr       = explode(',', $val['user_id']);
                foreach ($arr as $user_id) {
                    $score = $userModel->where(['id' => $user_id])->value('score');
                    if ($score <= $user_gold) {
                        $user_gold = $score;
                    }
                    $result = WalletService::change($user_id, 'gold', $user_gold,
                        'jiaquan_gold',
                        [],
                        '分红');
                    $result = WalletService::change($user_id, 'score', -$user_gold,
                        'jiaquan_score',
                        [],
                        '分红释放');
                }
                if ($result) {
                    $dividendLogModel->create([
                        'user_ids'      => $val['user_id'],
                        'user_num'      => $val['num'],
                        'all_golden'    => $user_gold,
                        'level'         => $key,
                        'dividend_type' => 2
                    ]);
                    echo '分佣成功';
                }
            }
        }
//        dump($order_amount);
//        dump($fenhongData);
//        dump($userData);
        exit();
        dump($order_amount);
        dump($orderData);
//        $childrenData = Children::where(['children_id'=>1958])->order('level asc')->column('member_id');
//        $userModel    = new User();
//        $userArray = [];
//        $key = -1;
//        foreach ($childrenData as $k=>$v){
//            $pa_rate = $userModel->where(['id'=>$v,'pa_rate'=>['gt',0]])->value('pa_rate');
//            if($pa_rate){
//                $key ++;
//                $userArray[$key]['user_id'] = $v;
//                $userArray[$key]['pa_rate'] = $pa_rate;
//            }
//        }
//        if(!empty($userArray[0]['pa_rate'])){
//            $is_two = true;
//            if($userArray[0]['pa_rate'] >= 15 || empty($userArray[1]['pa_rate'])){
//               $is_two = false;
//            }
//            $order_amount = 3000;
//            $gold =  bcmul($order_amount, ($userArray[0]['pa_rate'] / 100), 2);
//            $params['type']   = 'gold';
//            $params['amount'] = $gold;
//            $params['memo']   = 'PA点收益';
//            $params['id']     = $userArray[0]['user_id'];
//            $params['ext']['user_id']   = $userArray[0]['user_id'];
//            Db::transaction(function () use ($params) {
//                return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
//                    $params['memo']);
//            });
//            if($is_two){
//                $pa_rate = $userArray[1]['pa_rate'] - $userArray[0]['pa_rate'];
//                $gold =  bcmul($order_amount, ($pa_rate / 100), 2);
//                $params['type']   = 'gold';
//                $params['amount'] = $gold;
//                $params['memo']   = 'PA点收益';
//                $params['id']     = $userArray[1]['user_id'];
//                $params['ext']['user_id']   = $userArray[0]['user_id'];;
//                Db::transaction(function () use ($params) {
//                    return WalletService::change($params['id'], $params['type'], $params['amount'], 'order', $params['ext'],
//                        $params['memo']);
//                });
//            }
//        }
//        dump($arr);
        exit();
        $walletLogModel = new WalletLog();
        $accelerate_max = config('site.accelerate_max');
        $inser          = [];
        $accelerate_one = config('site.accelerate_one') / 100;
        $accelerate_all = config('site.accelerate_all') / 100;
        $sumScoresOne   = [];
        $tow_arr        = [];
        $sumScoresTwo   = [];
        $walletLogInfo  = $walletLogModel->where(['event' => 'release', 'type' => 'score'])->whereTime('createtime',
            'd')->select();
        if ($walletLogInfo) {
            foreach ($walletLogInfo as $k => $v) {
                if (isset($v['ext']['parent_user_id']) && $v['ext']['parent_user_id'] > 0) {
                    //分享释放
                    $parent_user_id = $v['ext']['parent_user_id'];
                    $amount         = abs($v['amount']);
                    if (isset($sumScoresOne[$v['ext']['parent_user_id']])) {
                        $sumScoresOne[$v['ext']['parent_user_id']] += $amount;
                    } else {
                        $sumScoresOne[$v['ext']['parent_user_id']] = $amount;
                    }
                    //团队加速
                    $children_level = db('user_children')->where([
                        'member_id' => $parent_user_id,
                        'level'     => 1
                    ])->count();
                    if ($children_level > 1) {
                        if ($children_level >= $accelerate_max) {
                            $children_level = $accelerate_max;
                        }
                        if (isset($tow_arr[$parent_user_id]['children_id'])) {
                            $cj_amount = $walletLogModel->whereIn('user_id',
                                $tow_arr[$parent_user_id]['children_id'])->where([
                                'event' => 'release',
                                'type'  => 'score'
                            ])->whereTime('createtime', 'd')->sum('amount');
                            if ($cj_amount) {
                                $cj_amount                     = abs($cj_amount);
                                $sumScoresTwo[$parent_user_id] = $cj_amount;
                            }
                        } else {
                            $tow_arr[$parent_user_id]['children_id'] = db('user_children')->where(['member_id' => $parent_user_id])->whereBetween('level',
                                [2, $children_level])->column('children_id');
                        }
                    }
                }
            }
        }
        dump($sumScoresTwo);
        dump($sumScoresOne);
        exit();
        foreach ($userData as $k => $v) {
            $walletLogInfo = $walletLogModel->where([
                'user_id' => $v['children_id'],
                'event'   => 'release',
                'type'    => 'score'
            ])->whereTime('createtime',
                'd')->find();
            if ($walletLogInfo) {
                $arr[$k]              = $v;
                $arr[$k]['score_one'] = abs($walletLogInfo['amount']);
            }
            $count = db('user_children')->where(['member_id' => $v['member_id'], 'level' => 1])->count();

            if ($count > 1) {
                if ($count >= $accelerate_max) {
                    $children_level = $accelerate_max;
                } else {
                    $children_level = count($userData);
                }
                $userData = db('user_children')->where(['member_id' => $v['member_id']])->whereBetween('level',
                    [2, $children_level])->select();
                if ($userData) {
                    foreach ($userData as $kk => $vv) {
                        $walletLogInfo = $walletLogModel->where([
                            'user_id' => $vv['children_id'],
                            'event'   => 'release',
                            'type'    => 'score'
                        ])->whereTime('createtime',
                            'd')->find();
                        if ($walletLogInfo) {
                            $tow_arr[$kk]          = $vv;
                            $tow_arr[$kk]['score'] = abs($walletLogInfo['amount']);
                        }
                    }
                    dump($tow_arr);
                }

            }
        }

//        dump($children_level);
        exit();
        $tow_arr  = [];
        $userData = db('user_children')->whereBetween('level', [2, $children_level])->select();
    }

    public function dailifenhong(
        $members,
        $team_amount,
        $currMemberLevel,
        $user_id,
        $currentCommissionLevel = 1,
        $currCommissionReward = 0,
        $currReward = 0.00
    ) {
        $array = [];
        foreach ($members as $v) {
            $currentAgent = User::where(['id' => $v])->find();
            if ($currentAgent) {
                if ($currentAgent->level > $currMemberLevel) {
                    $currentCommissionLevelRule = $this->getCommissionLevelRule($currentAgent->level);
                    if ($currentCommissionLevelRule) {
                        $commission = $this->caculateGoodsCommission($currentCommissionLevelRule, $team_amount);
                        if ($commission > 0) {
                            $currCommissionReward = $commission - $currReward;
                            if ($currCommissionReward > 0) {
                                $accelerate_scale_two = Acceleration::where([
                                    'status' => 1,
                                    'id'     => $currMemberLevel
                                ])->value('accelerate_scale');
                                db('agentreward_log')->insert([
                                    'user_id'              => $v,
                                    'commission'           => $currCommissionReward,
                                    'amount'               => $team_amount,
                                    'level'                => $currentAgent->level,
                                    'accelerate_scale'     => $currentCommissionLevelRule['accelerate_scale'],
                                    'accelerate_scale_two' => $accelerate_scale_two,
                                    'createtime'           => time()
                                ]);
                                $currReward += $currCommissionReward;
                            }
                        }
                    }
                    $currMemberLevel = $currentAgent->level;
                } elseif ($currentAgent->level == $currMemberLevel) {
                    //平级奖规则
                    $user_level = User::where(['id' => $user_id])->value('level');
                    if ($user_level != $currentAgent->level) {
                        $currentCommissionLevelRule = $this->getCommissionLevelRule($currentAgent->level);
                        if ($currentCommissionLevelRule) {
                            $commission = $this->caculateGoodsCommission($currentCommissionLevelRule, $team_amount,
                                'parallel_scale');
                            if ($commission > 0) {
                                $currCommissionReward = $commission;
                                if ($currCommissionReward > 0) {
                                    db('agentreward_log')->insert([
                                        'user_id'    => $v,
                                        'commission' => $currCommissionReward,
                                        'amount'     => $team_amount,
                                        'level'      => $user_level,
                                        'type'       => 2,
                                        'createtime' => time()
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 首页
     */
    public function jicha($user, $release, $level)
    {
        $childrenModel = new Children();
        $member_id     = $childrenModel->where(['children_id' => $user['id']])->order('level',
            'asc')->column('member_id');
        $this->dailifenhong($member_id, $release, $level, $user['id']);
    }

}
